package com.wehealth;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.umeng.analytics.MobclickAgent;
import com.wehealth.adapter.Adapter_PlanDay_new;
import com.wehealth.dm.DM_PlanDay_new;
import com.wehealth.dm.User;
import com.wehealth.util.DateUtil;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

@SuppressLint("ValidFragment")
public class Plan_Day extends Fragment {

	private ListView lv_planDay;
	private List<DM_PlanDay_new> plan_list;
	ProgressDialog pd = null;
	MainActivity activity;
	int weekday;
	private Adapter_PlanDay_new adapter;
	private User user;
	private static  String JSONResult;
	private static final int NET_ERROR = -100;
	
	
	public  Plan_Day()
	{
		weekday = 1; //默认星期一
				
		Log.i("init:", "Plan_Day"); 
	}
	
	
	public  Plan_Day(int iWeek)
	{
		weekday = iWeek;
		
		Log.i("weekday:",  Integer.toString(weekday)); 
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		return  inflater.inflate(R.layout.plan_day, null);
	}
	
	
	
	public void onActivityCreated(Bundle savedInstanceState){
		
		super.onActivityCreated(savedInstanceState);
		
		
		String strWeekday = "";
		
		switch(weekday)
		{
			case 1: strWeekday = "星期一";
				break;
				
			case 2: strWeekday = "星期二";
			break;
			
			case 3: strWeekday = "星期三";
			break;
			
			case 4: strWeekday = "星期四";
			break;
			
			case 5: strWeekday = "星期五";
			break;
			
			case 6: strWeekday = "星期六";
			break;
			
			case 7: strWeekday = "星期日";
			break;
		}
	
	   

	    activity = (MainActivity)getActivity();
	    user = activity.getUserInfo();
	    MobclickAgent.openActivityDurationTrack(false);
	    TextView title = (TextView)activity.findViewById(R.id.title_PlanDay);
		
	    title.setText(strWeekday);
	    
		
		
		lv_planDay = (ListView)activity.findViewById(R.id.lv_plan_day);
		
		//请数据列表
		connectServierGetData();

		//返回主页按钮-------------------------------------------------------//
		 Button bBack = (Button) activity.findViewById(R.id.bBack_PlanDay);
			
		 bBack.setOnClickListener(new View.OnClickListener()
			{
				public void onClick(View v)
				{
				    activity.switchContentHome();
				}
			});
			
		//------------------------------------------------------------------//
		
	}
	
	
	

	/**
	 * 渲染界面,显示数据
	 */
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message paramMessage) {
			//取消加载框
    		if(JSONResult!=null){
    		    BindList(JSONResult);
    		}else{
    			 activity.openDialogBt(NET_ERROR); 
    		}
		}
	};

	private void connectServierGetData(){
		
		new Thread(){
			@Override
			public void run(){
				try {
					GetListData();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			handler.sendEmptyMessage(0);
			}
		}.start();
	}
	
	
	
	private void  GetListData() throws IOException
	{
		String userID =String.valueOf(user.getUserId());
		String RecommendId = user.getRecommendID();
		
	
		String httpUrl = com.wehealth.util.GetUrl.Plan_GetHealthDay();
		 HttpPost httpRequest= new HttpPost(httpUrl);
		 
		 List <NameValuePair> params = new ArrayList <NameValuePair>();
		 
		 params.add(new BasicNameValuePair("userID",userID));
		 params.add(new BasicNameValuePair("recommendID",RecommendId)); 
		 String weekdayStr = String.valueOf(weekday);
		 params.add(new BasicNameValuePair("weekday",weekdayStr)); 
		 Log.d("SIMMON","Plan_Day  userID="+userID);
		 Log.d("SIMMON","Plan_Day  RecommendId="+	 RecommendId);
		 Log.d("SIMMON","Plan_Day  weekdayStr="+weekdayStr);
		 try
		 {
			 httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );
			
			 HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
			 
			 if(httpResponse.getStatusLine().getStatusCode() == 200)
			 {
				 JSONResult = EntityUtils.toString(httpResponse.getEntity());
				 Log.d("SIMMON","Plan_Day  JSONResult="+JSONResult);
			 }
		 }
		 catch(Exception e)
		 {
			
			 Log.e("error:",  e.toString());
			 
		 }

	}
	
	
    //将JSON数据绑定到LISTVIEW
    private void BindList(String strJSON){
       try{
    	   		plan_list = new ArrayList<DM_PlanDay_new>();
                JSONObject jsonObject = new JSONObject(strJSON); 
                JSONArray  aNews =  new JSONArray( jsonObject.getString("result") );  
                for(int i=0; i<aNews.length(); i++)
                    {
                	DM_PlanDay_new  playDay= new DM_PlanDay_new();
                	playDay.setID(aNews.getJSONObject(i).getString("ID"));
                	playDay.setTime(aNews.getJSONObject(i).getString("time"));
                	playDay.setPlanItemType(aNews.getJSONObject(i).getString("PlanItemType"));
                	playDay.setPlanItemTypeName(aNews.getJSONObject(i).getString("PlanItemTypeName"));
                	playDay.setPlanContent(aNews.getJSONObject(i).getString("planContent"));
                	playDay.setcontentIDs(aNews.getJSONObject(i).getString("contentIDs"));     	
                	playDay.setcontentValues(aNews.getJSONObject(i).getString("contentValues"));
                	playDay.setisRemind(aNews.getJSONObject(i).getString("isRemind"));         	
                	playDay.setisCompleted(aNews.getJSONObject(i).getString("isCompleted"));
                	plan_list.add(playDay);
                }
                Log.d("SIMMON","BindList aNews.length()= "+aNews.length());
                updateListViewData(plan_list);
            }
            catch(JSONException ex)
            {
                    Log.e("JSON Error: ", ex.toString()); 
            }
    }
	
    private  void updateListViewData(List<DM_PlanDay_new> datas ){
        ComparatorTime(datas);
        Adapter_PlanDay_new adapter = new Adapter_PlanDay_new(activity,datas);
        lv_planDay.setAdapter(adapter);
        lv_planDay.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int pos, long pos2) {
            	int planItemTypeValue = Integer.valueOf(plan_list.get(pos).getPlanItemType());
            	
            	if(planItemTypeValue < 8 && planItemTypeValue>3){
            		Plan_Day_info planinfo = new Plan_Day_info(plan_list.get(pos).getID(),plan_list.get(pos).getisCompleted(),weekday);
            		activity.switchContent(planinfo);
            	}else if(planItemTypeValue>=8 &&  planItemTypeValue < 12){
            		plan_day_info_sport_descrip planinfo = new plan_day_info_sport_descrip(plan_list.get(pos),weekday);
            		activity.switchContent(planinfo);
            	}else if(planItemTypeValue ==12){	
            		Plan_Day_record_weight planinfo = new Plan_Day_record_weight(plan_list.get(pos));
            		activity.switchContent(planinfo);
            	}else if(planItemTypeValue==1){
            		Plan_Day_record_blood_pressure planinfo = new Plan_Day_record_blood_pressure(plan_list.get(pos));
            		activity.switchContent(planinfo);
            	}else if(planItemTypeValue==2 ||planItemTypeValue==3 ){
            		Plan_Day_record_blood_sugar planinfo = new Plan_Day_record_blood_sugar(plan_list.get(pos));
            		activity.switchContent(planinfo);
            	}
            }
        });
        
    }
    

    
    private void ComparatorTime(List<DM_PlanDay_new> datas){
        
        Collections.sort(datas,new java.util.Comparator<DM_PlanDay_new>() {
            /** 
             *  
             * @param lhs 
             * @param rhs 
             * @return an integer < 0 if lhs is less than rhs, 0 if they are 
             *         equal, and > 0 if lhs is greater than rhs,比较数据大小时,这里比的是时间 
             */  
           @Override
           public int compare(DM_PlanDay_new time1, DM_PlanDay_new time2) {
               // TODO Auto-generated method stub
               Date rdate = DateUtil.stringToDate(time1.getTime()); 
               Date ldate = DateUtil.stringToDate(time2.getTime()); 
               if (ldate.before(rdate)) {  

                   return 1; 
                       }
               return -1;
           }
            
       });
    }
    
    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        MobclickAgent.onPageEnd("Plan_Day"); 
    }


    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        MobclickAgent.onPageStart("Plan_Day"); 
    }
}
